<?php


namespace app\api\controller;


use app\api\model\FoodListModel;
use app\api\model\FoodTypeModel;
use app\api\model\InfoTypeRecord;
use app\api\model\UserFoodAttrModel;
use app\api\model\UserFoodModel;
use app\api\model\UserFoodRecord;
use app\api\model\UserSportModel;
use app\common\controller\Api;
use function fast\e;

class Food extends Api
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 食物列表
     *
     */
    public function index()
    {
        $time_int = date('H',time());

        $type = input('post.type',0);

        $list = FoodTypeModel::getList($type);

        $this->success('请求成功',$list);
    }

    /**
     * 食物搜索
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function search()
    {
        //关键字  分页
        $keyword = input('post.keyword',"");
        $page = input('post.page',1);
        $pageSize = input('post.pageSize',10);

        //总数 和 总页数
        $total = FoodListModel::where('name','like','%'.$keyword.'%')->where('is_show',1)->count();
        $total_page = ceil($total/$pageSize);

        //列表
        $list = FoodListModel::where('name','like','%'.$keyword.'%')->where('is_show',1)->limit(($page - 1)*$pageSize,$pageSize)->select();

        $this->success('请求成功',['list'=>$list,'pageSize'=>$pageSize,'current_page'=>$page,'total_page'=>$total_page,'total'=>$total]);
    }

    /*
     * 食物汇总
     */

    public function takeFoods()
    {
        $today = date('Y-m-d',time());

        $day = input('post.day',$today);
        //打卡类型:1=早餐,2=午餐,3=晚餐,4=加餐,5饮水
        $type = input('post.type');
        if(empty($type)){
            $this->error('请传入打卡类型');
        }
        //[{"fid":3,"num":"10"},{"fid":4,"num":"10"},{"fid":2,"num":"10"},{"fid":1,"num":"10"}]
        $foods = input('post.foods');
//        $foods = '[{"fid":3,"num":"10"},{"fid":4,"num":"10"},{"fid":2,"num":"10"},{"fid":1,"num":"10"}]';
        $foods = html_entity_decode($foods);
        $foods_arr = json_decode($foods,true);

        $check = UserFoodModel::get(['user_id'=>$this->auth->id,'day'=>$day,'type'=>$type]);
        $user_food_model = new UserFoodAttrModel();
        if($check && $type < 4){
            $user_food = [];
            foreach ($foods_arr as $key => $val){
                $foods_detail = FoodListModel::get($val['fid']);
                if(!$foods_detail){
                    $this->error('当前食谱中包含已删除的食品');
                }
                //$foodsInfo['hot'] += $foods_detail['hot'] * $val['num'];
                $check->hot += $foods_detail['hot'] * $val['num'] / 100;
                //$foodsInfo['dietary'] += $foods_detail['dietary'] * $val['num'];
                $check->dietary += $foods_detail['dietary'] * $val['num'] / 100;
                //$foodsInfo['protein'] += $foods_detail['protein'] * $val['num'];
                $check->protein += $foods_detail['protein'] * $val['num'] / 100;
                //$foodsInfo['fat'] += $foods_detail['fat'] * $val['num'];
                $check->fat += $foods_detail['fat'] * $val['num'] / 100;
                //$foodsInfo['water'] += $foods_detail['water'] * $val['num'];
                $check->water += $foods_detail['water'] * $val['num'] / 100;
                $user_food[$key]['name'] = $foods_detail['name'];
                $user_food[$key]['food_value'] = $val['num'];
            }
            $check->save();
            foreach ($user_food as &$val){
                $val['pid'] = $check['id'];
            }
        }else{
            $model = new UserFoodModel();
            $user_food = [];
            $foodsInfo = [];
            $foodsInfo['user_id'] = $this->auth->id;
            $foodsInfo['day'] = $day;
            $foodsInfo['hot'] = 0;
            $foodsInfo['dietary'] = 0;
            $foodsInfo['protein'] = 0;
            $foodsInfo['fat'] = 0;
            $foodsInfo['water'] = 0;
            $foodsInfo['type'] = $type;
            foreach ($foods_arr as $key => $val){
                $foods_detail = FoodListModel::get($val['fid']);
                if(!$foods_detail){
                    $this->error('当前食谱中包含已删除的食品');
                }
                //$foodsInfo['hot'] += $foods_detail['hot'] * $val['num'];
                $foodsInfo['hot'] += $foods_detail['hot'] * $val['num'] / 100;
                //$foodsInfo['dietary'] += $foods_detail['dietary'] * $val['num'];
                $foodsInfo['dietary'] += $foods_detail['dietary'] * $val['num'] / 100;
                //$foodsInfo['protein'] += $foods_detail['protein'] * $val['num'];
                $foodsInfo['protein'] += $foods_detail['protein'] * $val['num'] / 100;
                //$foodsInfo['fat'] += $foods_detail['fat'] * $val['num'];
                $foodsInfo['fat'] += $foods_detail['fat'] * $val['num'] / 100;
                //$foodsInfo['water'] += $foods_detail['water'] * $val['num'];
                $foodsInfo['water'] += $foods_detail['water'] * $val['num'] / 100;
                $user_food[$key]['name'] = $foods_detail['name'];
                $user_food[$key]['food_value'] = $val['num'];
            }

            $model->data($foodsInfo);
            $model->save();
            $pid = $model->getLastInsID();
            foreach ($user_food as &$val){
                $val['pid'] = $pid;
            }
        }


        $user_food_model->saveAll($user_food);
        $this->success('请求成功');
    }

    /*
     * 今日打卡统计
     */
    public function todayFoodDetail()
    {
        $today = date('Y-m-d',time());

        $day = input('post.day',$today);

        $list = UserFoodModel::all(['day'=>$day,'user_id'=>$this->auth->id,'type'=>['<',5]]);

        $sum = [];
        $sum['hot'] = 0;
        $sum['dietary'] = 0;
        $sum['protein'] = 0;
        $sum['fat'] = 0;
        $sum['water'] = 0;
        $type_status = [];
        $type_status['zao'] = false;
        $type_status['zhong'] = false;
        $type_status['wan'] = false;
        foreach ($list as $val){
            $sum['hot'] += $val['hot'];
            $sum['dietary'] += $val['dietary'];
            $sum['protein'] += $val['protein'];
            $sum['fat'] += $val['fat'];
            $sum['water'] += $val['water'];
            switch ($val['type']){
                case 1:
                    $type_status['zao'] = true;
                    break;
                case 2:
                    $type_status['zhong'] = true;
                    break;
                case 3:
                    $type_status['wan'] = true;
                    break;
            }
        }

        $water_ids = UserFoodModel::where(['day'=>$day,'user_id'=>$this->auth->id,'type'=>5])->column('id');
        $foodAttrModel = new UserFoodAttrModel();

        $water = $foodAttrModel->where(['pid'=>['in',$water_ids]])->select();
        $water_sum = 0;
        if(!empty($water)){
            foreach ($water as $val){
                $water_sum += $val['food_value'];
            }
        }
        $data = [];

        foreach ($list as &$val){
            $val['sum'] = $val['hot'] + $val['dietary'] + $val['protein'] + $val['fat'] + $val['water'];
            if(empty($val['sum'])){
                $val['hot_bili'] = 0;
                $val['dietary_bili'] = 0;
                $val['protein_bili'] = 0;
                $val['fat_bili'] = 0;
                $val['water_bili'] = 0;
            }else{
                $hot = $val['hot'] / $val['sum'];
                $val['hot_bili'] = number_format($hot,2);
                $dietary = $val['dietary'] / $val['sum'];
                $val['dietary_bili'] =sprintf("%.2f",$dietary);
                $protein = $val['protein'] / $val['sum'];
                $val['protein_bili'] = number_format($protein, 2);
                $fat = $val['fat'] / $val['sum'];
                $val['fat_bili'] = number_format($fat,2);
                $val['water_bili'] = number_format($val['water'] / $val['sum'],2);
            }


        }

//        $this->success('请求成功',$list);

        $sum_bili = $sum['hot'] + $sum['dietary'] + $sum['protein'] + $sum['fat'] + $sum['water'];
        if(empty($sum_bili)){
            $sum['hot_bili'] = 0;
            $sum['dietary_bili'] = 0;
            $sum['protein_bili'] = 0;
            $sum['fat_bili'] = 0;
            $sum['water_bili'] = 0;
        }else{
            $sum['hot'] = round($sum['hot'],2);
            $sum['hot_bili'] = number_format($sum['hot'] / $sum_bili,2);
            $sum['dietary'] = round($sum['dietary'],2);
            $sum['dietary_bili'] = number_format($sum['dietary'] / $sum_bili,2);
            $sum['protein'] = round($sum['protein'],2);
            $sum['protein_bili'] = number_format($sum['protein'] / $sum_bili,2);
            $sum['fat'] = round($sum['fat'],2);
            $sum['fat_bili'] = number_format($sum['fat'] / $sum_bili,2);
            $sum['water'] = round($sum['water'],2);
            $sum['water_bili'] = number_format($sum['water'] / $sum_bili,2);
        }

        $data['list'] = $list;
        $data['type_status'] = $type_status;
        $data['sum'] = $sum;
        $data['water'] = $water;
        $data['water_sum'] = $water_sum;

        $sport = UserSportModel::all(['day'=>$day,'user_id'=>$this->auth->id,'dakatime'=>['>',0]]);
        $all_sport = UserSportModel::all(['day'=>$day,'user_id'=>$this->auth->id,'is_admin'=>1]);

        $data['sport'] = $sport;
        $data['all_sport'] = count($all_sport);
        $data['day'] = $day;

        $this->success('请求成功',$data);
    }


    /*
     **运动打卡
     */
    public function takeSportInfo()
    {
        $input = input('post.');
        $today = date('Y-m-d',time());
        if(!isset($input['sport_feel']) || empty($input['sport_feel'])){
            $this->error('请输入运动感受');
        }
        if(!isset($input['heart']) || empty($input['heart'])){
            $this->error('请输入心率');
        }
        if(!isset($input['sport_space']) || empty($input['sport_space'])){
            $this->error('请输入运动场地');
        }
        if(!isset($input['starttime']) || empty($input['starttime'])){
            $this->error('请输入开始时间');
        }

        if(!isset($input['endtime']) || empty($input['endtime'])){
            $this->error('请输入结束时间');
        }

        if(isset($input['id']) && !empty($input['id'])){
            $model = UserSportModel::get(['user_id'=>$this->auth->id,'id'=>$input['id']]);
            if(!$model){
                $this->error('当前方案不存在');
            }
            $input['dakatime'] = time();
            $input['day'] = date('Y-m-d',time());
            $model->allowField(true)->save($input);
            $this->success('打卡成功');
        }

        if(!isset($input['sport_name']) || empty($input['sport_name'])){
            $this->error('请输入运动名称');
        }
        $input['dakatime'] = time();
        $input['user_id'] = $this->auth->id;
        $input['day'] = date('Y-m-d',time());
        $model = new UserSportModel();
        $model->allowField(true)->data($input);

        $model->save();
        $this->success('打卡成功');
    }

    /*
     * 查看我的运动方案
     */
    public function mySportInfo()
    {
        $list = UserSportModel::all(['user_id'=>$this->auth->id,'is_admin'=>1,'day'=>date('Y-m-d')]);
        $this->success('请求成功',$list);
    }

    /*
     * 我的运动方案详情
     */
    public function mySportDetail()
    {
        $id = input('post.id');
        if(empty($id)) {
            $this->error('id不能为空');
        }
        $detal = UserSportModel::get($id);

        $this->success('请求成功',$detal);
    }


    /*
     * 食物汇总（增）
     */
    public function takeFoodRecord()
    {
        $str = input('post.str');
        $type_id = input('post.type_id');

        //$str = '[{"fid":3,"food_value":"10"},{"fid":4,"food_value":"10"},{"fid":2,"food_value":"10"},{"fid":1,"food_value":"10"}]';

        $foods = html_entity_decode($str);
        $foods_arr = json_decode($foods,true);

        $arr = [];
        foreach ($foods_arr as $val){

            $data = [
                'user_id'=>$this->auth->id,
                'fid'=>$val['fid'],
                'food_value'=>$val['food_value'],
                'type_id'=>$type_id
            ];
            $arr[] = $data;
        }

        $model = new UserFoodRecord();


        $model->saveAll($arr);

        $this->success('请求成功');

    }
    /*
     * 食物汇总（查）
     */
    public function getFoodRecord()
    {
        $type_id = input('post.type_id');

        $model = new UserFoodRecord();

        if(empty($type_id)){
            $this->error('缺少参数');
        }
        $list = $model->all(['user_id'=>$this->auth->id,'type_id'=>$type_id]);

        $this->success('请求成功',$list);

    }

    /*
     * 食物汇总（删）
     */
    public function delFoodRecord()
    {
        $id = input('post.id');

        $model = new UserFoodRecord();

        if(empty($id)){
            $this->error('缺少参数');
        }
        $model->where('id','in',$id)->delete();

        $this->success('删除成功');

    }
}